package com.hankol.community

import android.content.Intent
import android.view.View
import android.webkit.WebView
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.*
import com.baselibrary.Constants.DYNAMIC_TYPE_IMG
import com.baselibrary.activity.BaseActivity
import com.baselibrary.bean.CommentEnum
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.ArticleWebViewClient
import com.baselibrary.view.share.SharePopupWindow
import com.google.android.material.appbar.AppBarLayout
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.bean.ArticleDetailBean
import com.hankol.community.bean.ShowShare2Bean
import com.hankol.community.databinding.ActivityArticleDetailBinding
import com.hankol.community.viewmodel.CommunityViewModel
import com.hankol.message.HKIMUtils
import com.liaoinstan.springview.utils.DensityUtil
import com.like.LikeButton
import com.like.OnLikeListener
import com.okhttp.comment.CommentBean
import com.okhttp.comment.CommentConstant
import com.okhttp.comment.IPCommentListener
import com.umeng.socialize.bean.SHARE_MEDIA
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


/**
 * @description 文章详情
 * 没有点赞功能
 *@author wxp
 */
@Route(path = ActivityRouter.COMMUNITY.ARTICLE_DETAIL)
class ArticleDetailActivity : BaseActivity(), View.OnClickListener {

    private lateinit var binding: ActivityArticleDetailBinding
    private lateinit var mViewModel: CommunityViewModel
    var aid = 0L
    private var mPage: Int = 0
    private var mCommentBean: CommentBean.DataBean? = null
    private var mToppingCommentId: Long = 0
    private var mDataBean: ArticleDetailBean? = null
    val communityHelp: CommunityHelp = ActivityRouter.getARouterInterface(ActivityRouter.COMMUNITY.COMMUNITY_HELP)
    private var mShowSharePop: SharePopupWindow? = null
    val SHARE_IMG = 1 //图片分享
    override fun getLayoutId(): Int {
        return R.layout.activity_article_detail
    }

    override fun init() {
        //获取页面开始时间
        SensorsDataManager.instance.onCreateTime()
        SensorsDataManager.instance.setFormPagePos("文章")
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }

        binding = getDataBinding<ActivityArticleDetailBinding>()
        mViewModel = getActivityViewModelProvider(this).get(CommunityViewModel::class.java)
        if (intent.extras.checkNotNull()) {
            if (ARouterUtils.parseParams(intent.extras!!, "aid").size > 0) {
                aid = ARouterUtils.parseParams(intent.extras!!, "aid")[0].toLong()
            }
        }
        initView()
        initListener()
        initObserver()
        loadData()
    }

    private fun initView() {
        binding.tvContentTitle.paint.isFakeBoldText = true
        binding.ablTop.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            val offset = ScreenUtils.dpToPx(109)
            if (-verticalOffset in 0..offset) {
                binding.llNickHead.visibility = View.GONE
                binding.tvTitle.visibility = View.VISIBLE
            } else {
                binding.llNickHead.visibility = View.VISIBLE
                binding.tvTitle.visibility = View.GONE
            }
        })
        binding.smartRefresh.setOnRefreshListener {
            mPage = 1
            loadData()
        }
        binding.smartRefresh.setEnableLoadMore(false)
        //显示分享功能
        binding.includeCommentView.llShare.visibility = View.VISIBLE
        //隐藏点赞功能
        binding.includeCommentView.llCommentGive.visibility = View.GONE
        binding.BaseCommentViewImageDynamic.setEmptyImgSize(DensityUtil.dip2px(applicationContext, 230f), DensityUtil.dip2px(applicationContext, 230f))
        binding.BaseCommentViewImageDynamic.setEmptyTopMargin(DensityUtil.dip2px(applicationContext, 20f))
        binding.BaseCommentViewImageDynamic.setAdapter(this, IPCommentListener(this, binding.BaseCommentViewImageDynamic))
        mViewModel.reqArticleDetailRedNumPlus(aid)
    }

    fun initObserver() {
        mViewModel.commentListLiveData.observe(this, Observer {
            binding.smartRefresh.finishRefresh()
            if (it != null) {
                if (it.totalCount == 0) {
                    binding.BaseCommentViewImageDynamic.isEmptyView(false)
                }
                binding.includeCommentView.tvCommentComCount.text = if (it.totalCount == 0) "抢首评" else NumberUtils.formatBigNum(it.totalCount.toString())
                binding.BaseCommentViewImageDynamic.commentNetData(it, mPage)
                mCommentBean = it

                if (mToppingCommentId > 0) {
                    binding.tvPictureDetSumComment.post { binding.scrollView.smoothScrollTo(0, binding.tvPictureDetSumComment.top) }
                }
                mPage++
                return@Observer
            }
        })
        mViewModel.articleDetailLD.observe(this, Observer {
            setDataInfo(it)
        })
        //请求好友列表
        mViewModel.friendLiveData.observe(this, Observer {
            mShowSharePop?.setShareFriendAdapter(mViewModel.changeFriend(it))
        })
        //收藏&取消收藏
        mViewModel.collectionLiveData.observe(this, Observer { it ->
            if (it) {
                mDataBean?.let {
                    it.favoriteNum = if (binding.includeCommentView.llCommentCollection.isSelected) {
                        ToastUtils.showShort(applicationContext, "取消收藏")
                        it.favoriteNum.minus(1)
                    } else {
                        ToastUtils.showShort(applicationContext, "收藏成功")
                        it.favoriteNum.plus(1)
                    }
                    upCollectionSate(it.favorited != 1, it.favoriteNum)
                    it.favorited = if (binding.includeCommentView.llCommentCollection.isSelected) 1 else 0
                }
            }
        })
        //关注&取消关注
        mViewModel.followLiveData.observe(this, Observer {
            setFollowState(!binding.imgFollowState.isSelected)
            if (!binding.imgFollowState.isSelected) {
                //关注
                mDataBean?.let { ub ->
                    HKIMUtils.followSendMsg(ub.uid.toInt(), it.friendState)
                }
            }
        })
        //阅读数+1
        mViewModel.articleDetailNumPlusLD.observe(this, Observer { })
    }

    private fun setDataInfo(bean: ArticleDetailBean?) {
        mDataBean = bean
        bean?.let {
            binding.vhivHead.setData(it.userIcon.checkValue(), it.isFans == 1)
            binding.vhivContentHead.setData(it.userIcon.checkValue(), it.isFans == 1)
            val userBean = SpUtils.getInstance().loadUserBean.data
            binding.vhivBottomHead.setData(userBean.icon, userBean.isFans == 1)
            binding.tvTopNick.text = it.userName.checkValue()
            binding.tvContentNick.text = it.userName.checkValue()
            binding.tvTopFansNum.text = "${NumberUtils.formatBigNum("${it.fansNum}")}粉丝"
            binding.tvContentTitle.text = it.title.checkValue()
            binding.tvPublishTime.text = "${TimeUtil.fromToday(it.ctime)}  ${NumberUtils.formatBigNum("${it.readNum}")}阅读"
            val mWeb = WebView(this)
            mWeb.settings.javaScriptEnabled = true
            mWeb.settings.textZoom = 100
            mWeb.settings.builtInZoomControls = false
            mWeb.settings.setSupportZoom(false)
            mWeb.settings.displayZoomControls = false
            mWeb.webViewClient = ArticleWebViewClient()
            mWeb.settings.defaultTextEncodingName = "utf-8"
            mWeb.loadData(it.content.checkValue().replace("style=\"height:.+?px; width:.+?px\" ".toRegex(), "style=\"height:100%; width:100%\""), "text/html; charset=UTF-8", null)
            //mWeb.loadData(ArticleWebViewClient.repairContent(response.getData().getContent()), "text/html; charset=UTF-8", "UTF-8");
            binding.webViewParent.addView(mWeb)
            //收藏数
            upCollectionSate(it.favorited == 1, it.favoriteNum)
            //分享数
            upShareSate(it.shareNum)
            binding.tvPictureDetSumComment.text = "共${it.commentNum}条评论"
            //关注状态
            setFollowState(it.focus == 1)
        }
        binding.smartRefresh.finishRefresh()
    }

    //关注状态
    private fun setFollowState(focus: Boolean) {
        binding.imgFollowState.isSelected = focus
        binding.imgFollowStateTop.isSelected = focus
        binding.imgFollowState.setImageResource(if (focus) R.drawable.ic_picture_true_follow else R.drawable.ic_picture_flase_follow)
        binding.imgFollowStateTop.setImageResource(if (focus) R.drawable.ic_picture_true_follow else R.drawable.ic_picture_flase_follow)
        SpUtils.getInstance().loadUserBean?.let {
            binding.imgFollowState.visibility = if (it.data.id == mDataBean?.uid) View.GONE else View.VISIBLE
            binding.imgFollowStateTop.visibility = if (it.data.id == mDataBean?.uid) View.GONE else View.VISIBLE
        }
    }

    /**
     * 更新收藏状态
     */
    fun upCollectionSate(isFavorited: Boolean, favoriteNum: Int) {
        binding.includeCommentView.tvCommentConCount.text = if (favoriteNum == 0) "收藏" else NumberUtils.formatBigNum(favoriteNum.toString())
        binding.includeCommentView.llCommentCollection.isSelected = isFavorited
        binding.includeCommentView.ivCommentConState.isLiked = isFavorited
    }

    /**
     * 更新分享状态
     */
    fun upShareSate(shareNum: Int) {
        binding.includeCommentView.tvShareCount.text = if (shareNum == 0) "分享" else NumberUtils.formatBigNum(shareNum.toString())
    }

    fun loadData() {
        mViewModel.reqArticleDetail(aid)
        mViewModel.reqCommentList(mPage, aid, mToppingCommentId, CommentEnum.COMMENT_ARTICLE.commentType)
    }

    fun initListener() {
        binding.imgBack.setOnClickListener(this)
        binding.imgShare.setOnClickListener(this)
        binding.imgFollowState.setOnClickListener(this)
        binding.imgFollowStateTop.setOnClickListener(this)
        binding.tvPictureDetComment.setOnClickListener(this)
        binding.vhivContentHead.setOnClickListener(this)
        binding.tvContentNick.setOnClickListener(this)
        binding.tvTopNick.setOnClickListener(this)
        binding.vhivHead.setOnClickListener(this)

        binding.includeCommentView.llShare.setOnClickListener(this)
        binding.BaseCommentViewImageDynamic.setEmptyViewListener(this)
        binding.includeCommentView.llCommentSaySomething.setOnClickListener(this)
        binding.includeCommentView.llCommentJumpCom.setOnClickListener(this)
        binding.includeCommentView.llCommentCollection.setOnClickListener(this)
        binding.includeCommentView.ivCommentConState.setOnLikeListener(object : OnLikeListener {
            override fun liked(likeButton: LikeButton?) {
                mDataBean?.let {
                    //收藏
                    mViewModel.reqCollection(true, 1, it.id)
                }
            }

            override fun unLiked(likeButton: LikeButton?) {
                mDataBean?.let {
                    //取消收藏
                    mViewModel.reqCollection(false, 1, it.id)
                }
            }
        })
        binding.includeOnlyShareWx.tvShare2Wx.setOnClickListener(this)
        binding.includeOnlyShareWx.tvShare2WxCircle.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.img_back -> finish()
            R.id.vhiv_head, R.id.vhiv_content_head, R.id.tv_content_nick, R.id.tv_top_nick -> {
                if (DoubleUtils.isFastDoubleClick()) return
                val hashMap = HashMap<String, Any>()
                hashMap[BaseConstant.USER_ID] = "${mDataBean?.uid}"
                ARouterUtils.jump(ActivityRouter.MINE_CENTER.USER_INFO, hashMap)
            }
            //关注&取消关注
            R.id.img_follow_state, R.id.img_follow_state_top -> {
                mDataBean?.let {
                    mViewModel.reqFollow(this, !binding.imgFollowStateTop.isSelected, 1, it.uid)
                }
            }
            R.id.ll_comment_collection -> {
                //收藏
                mDataBean?.let {
                    mViewModel.reqCollection(!binding.includeCommentView.llCommentCollection.isSelected, 1, it.id)
                }
            }
            R.id.img_share, R.id.ll_share -> {
                if (DoubleUtils.isFastDoubleClick()) return
                //分享
                mDataBean?.let {
                    mShowSharePop = mViewModel.showShare(articleBean2showShare(it), this, communityHelp)
                    mViewModel.reqFriendList()
                }
            }
            R.id.ll_comment_jumpCom -> {
                if (DoubleUtils.isFastDoubleClick()) return
                //跳转评论位置
                binding.BaseCommentViewImageDynamic.post { binding.scrollView.smoothScrollTo(0, binding.tvPictureDetSumComment.top) }
                //评论弹窗
                communityHelp.openCommentActivity(this, 4, aid.toInt(), binding.includeCommentView.tvCommentSaySomething.text.toString().trim(), mDataBean?.userName.checkValue(), false, CommentConstant.COMMENT_REQUESTCODE)
            }
            R.id.ll_base_comment_empty, R.id.tv_pictureDet_comment, R.id.ll_comment_saySomething -> {
                if (DoubleUtils.isFastDoubleClick()) return
                //进行评论
                BaseConstant.loadCommentEventBusBean("专栏文章", "内容详情页")
                communityHelp.openCommentActivity(this, 4, aid.toInt(), binding.includeCommentView.tvCommentSaySomething.text.toString().trim(), mDataBean?.userName.checkValue(), false, CommentConstant.COMMENT_REQUESTCODE)
            }
            R.id.tv_share2_wx -> {
                if (DoubleUtils.isFastDoubleClick()) return
                SensorsDataManager.instance.quickShareClick("文章", mDataBean?.title.checkValue())
                //分享到微信
                if (mDataBean.checkNotNull()) {
                    val shareUrl = AppUtils.getSaveShareHostUrl() + "/html/wineGod/wineColumn.html?id=" + mDataBean?.id
                    UMShareUtils.shareWeb(this, SHARE_MEDIA.WEIXIN, shareUrl, if (mDataBean?.coverLong.checkNotNull()) mDataBean?.coverLong.checkValue() else "" , mDataBean?.title, mDataBean?.searchWord.checkValue())
                }
            }
            R.id.tv_share2_wx_circle -> {
                if (DoubleUtils.isFastDoubleClick()) return
                SensorsDataManager.instance.quickShareClick("文章", mDataBean?.title.checkValue())
                //分享到朋友圈
                if (mDataBean.checkNotNull()) {
                    val shareUrl = AppUtils.getSaveShareHostUrl() + "/html/wineGod/wineColumn.html?id=" + mDataBean?.id
                    UMShareUtils.shareWeb(this, SHARE_MEDIA.WEIXIN_CIRCLE, shareUrl, if (mDataBean?.coverLong.checkNotNull()) mDataBean?.coverLong.checkValue() else "" , mDataBean?.title, mDataBean?.searchWord.checkValue())
                }
            }
        }
    }

    private fun articleBean2showShare(bean: ArticleDetailBean): ShowShare2Bean {
        return ShowShare2Bean().apply {
            id = aid
            uid = bean.uid
            isFans = bean.isFans
            headUrl = bean.userIcon
            showType = DYNAMIC_TYPE_IMG
            name = bean.userName
            cover = bean.coverLong.checkValue()
            title = bean.title.checkValue()
            content = bean.searchWord.checkValue()
            url = Constants.COLUMN_DETAIL_SHARE_URL + id
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        binding.BaseCommentViewImageDynamic.commentOnResult(requestCode, resultCode, data)
        binding.BaseCommentViewImageDynamic.setSayContent(requestCode, resultCode, data, binding.includeCommentView.tvCommentSaySomething, CommentConstant.COMMENT_DEF_CONTENT_VERSION_1)
        val commentNum: Int = binding.BaseCommentViewImageDynamic.upCommentNum(requestCode, resultCode, data, mDataBean?.commentNum!!, binding.includeCommentView.tvCommentComCount)
        if (commentNum != -1) {
            mDataBean?.commentNum = commentNum
            binding.tvPictureDetSumComment.text = "共${commentNum}条评论"
        }
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_follow_and_cancel) {
            mViewModel.reqArticleDetail(aid)
        }
    }

    override fun onDestroy() {
        mDataBean?.let {
            if (it.favorited == 0) //取消收藏
                EventBusUtils.sendNotify(MessageBus.msgId_article_collection_false)
        }
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        //获取页面结束时间
        SensorsDataManager.instance.onDestroyTime()
        if (SensorsDataManager.instance.getBrowseTime() != 0L) {
            SensorsDataManager.instance.browseArticle(if (mDataBean?.isTop == 1) "置顶文章" else "非置顶文章", mDataBean?.title.checkValue(), mDataBean?.columnName.checkValue())
        }
    }
}